﻿using Common.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utility
{
    public class BeflamToolManager
    {
        /// <summary>
        /// 获取Schema
        /// </summary>
        /// <param name="url">请求url</param>
        /// <param name="appId">应用名</param>
        /// <param name="sessionID">session</param>
        /// <param name="entitySchemaID">表名</param>
        /// <returns></returns>
        public SchemaData GetSchema(string url, string appId, string sessionID, string entitySchemaID)
        {
            try
            {
                HttpHelper httphelper = new HttpHelper();
                var jsonData = new
                {
                    appId = appId,
                    sessionID = sessionID,
                    assembly = "Beflam.Framework",
                    module = "Beflam.Framework.Service.EntitySchemaService",
                    function = "Refresh",
                    data = new
                    {
                        appID = appId,
                        entitySchemaID = entitySchemaID
                    }
                };
                string fieldpart = httphelper.PostRequest(url, jsonData);
                return JsonConvert.DeserializeObject<SchemaData>(fieldpart);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sessionID">sessionid</param>
        /// <param name="filename">模板名称</param>
        /// <param name="gridData">模板数据</param>
        /// <param name="Columns">列数</param>
        public void SaveFieldTemp(string url, string sessionID, string filename, List<GridDataItem> gridData, int Columns)
        {
            try
            {
                HttpHelper httphelper = new HttpHelper();
                var jsonData = new
                {
                    appId = "framework",
                    sessionID = sessionID,
                    assembly = "Beflam.Framework",
                    module = "Beflam.Framework.Service.CodeUtilPro.CodeUtilProService",
                    function = "Save",
                    data = new
                    {
                        Columns = Columns,
                        DataStatus = "ADDED",
                        DbKey = "",
                        EntitySource = "codeUtilProfile",
                        FileName = filename,
                        datas = gridData
                    }
                };
                string fieldpart = httphelper.PostRequest(url, jsonData);

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        /// <param name="url"></param>
        /// <param name="sessionID"></param>
        /// <param name="filename">模板名称</param>
        public void DeleteFieldTemp(string url, string sessionID, string filename)
        {
            try
            {
                HttpHelper httphelper = new HttpHelper();
                var jsonData = new
                {
                    appId = "framework",
                    sessionID = sessionID,
                    assembly = "Beflam.Framework",
                    module = "Beflam.Framework.Service.CodeUtilPro.CodeUtilProService",
                    function = "Delete",
                    data = filename
                };
                string fieldpart = httphelper.PostRequest(url, jsonData);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }



        /// <summary>
        /// 保存scheam
        /// </summary>
        /// <param name="url"></param>
        /// <param name="appId"></param>
        /// <param name="sessionID"></param>
        /// <param name="table"></param>
        /// <param name="datas"></param>
        public void SaveScheam(string url, string appId, string sessionID, string table, List<DataSourceItemex> datas)
        {
            try
            {
                HttpHelper httphelper = new HttpHelper();
                var jsonData = new
                {
                    appId = appId,
                    sessionID = sessionID,
                    assembly = "Beflam.Framework",
                    module = "Beflam.Framework.Service.EntitySchemaService",
                    function = "Save",
                    data = new
                    {
                        appID = appId,
                        fields = new
                        {
                            SCHEMA_NAME = table,
                            PRJ_NO = appId,
                            DESCRIPTION = "",
                            OBJTYPE = "",
                            ROWS = 0,
                            DATASIZE = "",
                            INDEXSIZE = "",
                            RESERVEDSIZE = "",
                            UNUSEDSIZE = "",
                            CREATEDATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                            MODIFYDATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
                        },
                        datas = datas
                    }
                };
                string fieldpart = httphelper.PostRequest(url, jsonData);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// 保存创建布局
        /// </summary>
        /// <param name="url"></param>
        /// <param name="sessionid"></param>
        /// <param name="tablename"></param>
        /// <param name="fieldData"></param>
        /// <param name="apiEntity"></param>
        /// <param name="type"></param>
        /// <param name="orderField"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public string SaveField(string url, string sessionid, string tablename, FieldPartLayoutData fieldData, SchemaData apiEntity, string type, List<string> orderField, int columns)
        {
            try
            {
                double rowIndex = 0;
                double colIndex = 0;
                //foreach (GridDataItem fielditem in fieldData.data.gridData)
                List<GridDataItem> listsoursegriditem = fieldData.data.gridData;

                List<GridDataItem> listgriditem = new List<GridDataItem>();

                List<string> listlist = new List<string>() { "CREATEUSER", "CREATEDATE", "MODIFYDATE", "MODIFYUSER" };

                //先删除存档
                //ToolManager toolManager = new ToolManager();

                DeleteFieldTemp(url, sessionid, $"{tablename}_{type}");
                foreach (string fielditem in orderField)
                {
                    //GridDataItem griditem = new GridDataItem();

                    GridDataItem sousegrid = listsoursegriditem.FirstOrDefault(a => a.FIELD_NAME.ToUpper() == fielditem.ToUpper());
                    //不存在则跳出本次循环
                    if (sousegrid == null) continue;



                    sousegrid.ROW = rowIndex;
                    sousegrid.COL = colIndex;
                    if (string.IsNullOrWhiteSpace(sousegrid.COLUMNS))
                    {
                        sousegrid.COLUMNS = "4";
                    }

                    //获取Schema属性
                    var objField = apiEntity.data.DataSource.FirstOrDefault(a => a.FLD_NAME.ToUpper() == sousegrid.FIELD_NAME.ToUpper());

                    if (objField != null)
                    {
                        if (type == "ADDNEW")
                        {
                            //跳过自增
                            if (objField.FLD_AUTOINCREMENT > 0)
                            {
                                sousegrid.NG_COMPONENT_STATUS = 2;
                                continue;
                            }
                        }
                        else if (type == "EDIT" || type == "DEF")
                        {
                            //主键不可编辑
                            if (objField.FLD_PRIMARYKEY > 0 || objField.FLD_AUTOINCREMENT > 0)
                            {
                                sousegrid.NG_COMPONENT_STATUS = "1";//只读
                            }
                        }
                    }

                    //创建时间等四个字段只读状态
                    if (listlist.Contains(fielditem))
                    {
                        sousegrid.NG_COMPONENT_STATUS = "1";//只读
                    }

                    //如果不是创建修改4个字段,且控件是显示状态
                    if (sousegrid.NG_COMPONENT_STATUS.ToString() != "2")
                    {
                        colIndex += sousegrid.COLSPAN;
                    }
                    if (colIndex > columns)
                    {
                        rowIndex += 1;
                        colIndex = 0;
                    }
                    listgriditem.Add(sousegrid);
                }

                //保存布局           
                SaveFieldTemp(url, sessionid, $"{tablename}_{type}", listgriditem, columns);
                //MessageBox.Show("创建成功");
                //text_filename.Text = $"{tablename}_{type}";
                return $"{tablename}_{type}";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public DataSourceItemex ConvertST(DataSourceItem item)
        {
            try
            {
                DataSourceItemex newitem = new DataSourceItemex();
                newitem.SCHEMA_NAME = item.SCHEMA_NAME;
                newitem.PRJ_NO = item.PRJ_NO;
                newitem.FLD_NAME = item.FLD_NAME;
                newitem.FLD_POS = item.FLD_POS;
                newitem.FLD_PRIMARYKEY = item.FLD_PRIMARYKEY;
                newitem.FLD_AUTOINCREMENT = item.FLD_AUTOINCREMENT;
                newitem.FLD_DATATYPE = item.FLD_DATATYPE;
                newitem.FLD_LENGTH = item.FLD_LENGTH;
                newitem.FLD_DEC = item.FLD_DEC;
                newitem.FLD_DESCRIPTION = item.FLD_DESCRIPTION;
                newitem.FLD_DATASQLTYPE = item.FLD_DATASQLTYPE;
                newitem.FLD_NULLABLE = item.FLD_NULLABLE;
                newitem.__ObjectState = "Modified";
                return newitem;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}
